﻿using System;
using System.Text;

namespace SW.Lite.Infrastructure.Helpers
{
    /// <summary>
    ///     Class RandomHelper.
    /// </summary>
    public class RandomHelper
    {
        private static RandomHelper _instance;

        /// <summary>
        ///     The rand
        /// </summary>
        private readonly Random _rand;

        /// <summary>
        ///     The rand character
        /// </summary>
        private readonly char[] _randChar =
        {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
            'W', 'X', 'Y', 'Z'
        };

        public RandomHelper()
        {
            _rand = new Random(unchecked((int) DateTime.Now.Ticks));
        }

        /// <summary>
        ///     Gets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public static RandomHelper Instance
        {
            get { return _instance ?? (_instance = new RandomHelper()); }
        }

        /// <summary>
        ///     根据规则随机生成字符串
        /// </summary>
        /// <param name="pattern">伪模态字符串："?"代表一个字符，"#"代表一个一位数字，"*"代表一个字符串或一个一位数字</param>
        /// <param name="caseSensitive">大小写敏感</param>
        /// <returns>随机字符串</returns>
        public string RandomString(string pattern, bool caseSensitive = false)
        {
            if (!pattern.Contains("#") && !pattern.Contains("?") && !pattern.Contains("*"))
                return pattern;

            var nums = pattern.ToCharArray();
            var sb = new StringBuilder();
            for (var i = 0; i < nums.Length; i++)
            {
                switch (nums[i])
                {
                    case '?':
                        nums[i] = caseSensitive ? _randChar[_rand.Next(10, 35)] : _randChar[_rand.Next(10, 62)];
                        break;
                    case '#':
                        nums[i] = _randChar[_rand.Next(0, 10)];
                        break;
                    case '*':
                        nums[i] = caseSensitive ? _randChar[_rand.Next(35)] : _randChar[_rand.Next(62)];
                        break;
                }

                sb.Append(nums[i]);
            }

            return sb.ToString();
        }
    }
}